import axios from 'axios'
import { User } from '../types/user'

export interface PaymentOrder {
  id: string
  courseId: string
  userId: string
  amount: number
  status: 'PENDING' | 'PAID' | 'FAILED'
  paymentMethod: 'ALIPAY' | 'WECHAT' | 'CREDIT_CARD'
  createdAt: Date
  updatedAt: Date
}

export interface PaymentResult {
  orderId: string
  transactionId: string
  status: 'SUCCESS' | 'FAILED'
  amount: number
}

export const paymentService = {
  async createOrder(courseId: string, userId: string) {
    try {
      const response = await axios.post('/api/payments/create', { courseId, userId })
      return response.data as PaymentOrder
    } catch (error) {
      throw new Error('创建订单失败')
    }
  },

  async processPayment(orderId: string, paymentMethod: string) {
    try {
      const response = await axios.post(`/api/payments/${orderId}/pay`, { paymentMethod })
      return response.data as PaymentResult
    } catch (error) {
      throw new Error('支付处理失败')
    }
  },

  async getPaymentHistory(userId: string) {
    try {
      const response = await axios.get(`/api/payments/history/${userId}`)
      return response.data as PaymentOrder[]
    } catch (error) {
      throw new Error('获取支付历史失败')
    }
  },

  async refundOrder(orderId: string) {
    try {
      const response = await axios.post(`/api/payments/${orderId}/refund`)
      return response.data
    } catch (error) {
      throw new Error('退款失败')
    }
  }
}
